﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TableTop.DataManagement.Addon
{
    public class Addon
    {
        protected Assembly AddonAssembly
        {
            get;
            set;
        }

        public Guid ID
        {
            get
            {
                if (this.EntryPoint != null)
                    return this.EntryPoint.GUID;
                else
                    return Guid.Empty;
            }
        }

        public IAddonEntryPoint EntryPoint
        {
            get;
            private set;
        }

        public AddonInfo Information
        {
            get
            {
                AddonInfo aiInfo = null;

                if (this.EntryPoint != null)
                    aiInfo = new AddonInfo(this.EntryPoint.Name,
                                           this.EntryPoint.Description,
                                           this.EntryPoint.GUID,
                                           this.EntryPoint.AddonIcon);
                return aiInfo;
            }
        }

        public Addon(String Filename)
        {
            this.InitializeAddon(Filename);
        }

        private void InitializeAddon(String Filename)
        {
            Type[] AssemblyTypes = null;

            this.AddonAssembly = Assembly.LoadFrom(Filename);
            AssemblyTypes = this.AddonAssembly.GetExportedTypes();

            foreach (Type t in AssemblyTypes)
            {
                Type iaepInterface = null;
                iaepInterface = t.GetInterface(typeof(IAddonEntryPoint).Name);
                if (iaepInterface != null)
                {
                    this.EntryPoint = (IAddonEntryPoint)this.AddonAssembly.CreateInstance(t.FullName);
                    break;
                }
            }
        }
    }
}
